package com.dense.kuiniu.bookborrow.business.home;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LanguageUtils;
import com.dense.kuiniu.bookborrow.MainActivity;
import com.dense.kuiniu.bookborrow.R;
import com.dense.kuiniu.bookborrow.base.BaseFragment;
import com.dense.kuiniu.bookborrow.base.ClickHelper;
import com.dense.kuiniu.bookborrow.business.entity.BorrowBookInfo;
import com.dense.kuiniu.bookborrow.business.entity.ReaderInfo;
import com.dense.kuiniu.bookborrow.business.event.USBChangeEvent;
import com.dense.kuiniu.bookborrow.business.home.back.BackScanBookDelegate;
import com.dense.kuiniu.bookborrow.business.home.borrow.BorrowScanBookDelegate;
import com.dense.kuiniu.bookborrow.business.home.query.QueryBookByUser;
import com.dense.kuiniu.bookborrow.business.home.renew.RenewBookDelegate;
import com.dense.kuiniu.bookborrow.device.DeviceManager;
import com.dense.kuiniu.bookborrow.dialog.PasswordInsureDialog;
import com.dense.kuiniu.bookborrow.net.SocketChecker;
import com.dense.kuiniu.bookborrow.receiver.SystemTTS;
import com.dense.kuiniu.bookborrow.setting.SettingActivity;
import com.dense.kuiniu.bookborrow.view.dialog.PutCardDialog;
import com.dense.kuiniu.bookborrow.xjSetting.listener.EventAction;
import com.dense.kuiniu.bookborrow.xjSetting.manager.PingBaoManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cc.lotuscard.LotusCardUtils;
import io.reactivex.rxjava3.functions.Consumer;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2020/8/6
 */
public class HomeDelegate extends BaseFragment {

    @BindView(R.id.tv_device_number)
    TextView mTvDeviceNumber;
    @BindView(R.id.tv_device_info)
    TextView mTvDeviceInfo;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    private PasswordInsureDialog dialog;
    private boolean hasFoundCardReader = false;

    public static HomeDelegate getInstance() {
        return new HomeDelegate();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.delegate_home;
    }

    @Override
    protected void init() {
        mTvVersion.setText(String.format("%s%s", getString(R.string.text_version), AppUtils.getAppVersionName()));
        EventBus.getDefault().register(this);

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (dialog != null) {
            dialog.hide();
        }
        PingBaoManager.getInstance().updateClickTime();
        PingBaoManager.getInstance().setOpenPingbao(true);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        PingBaoManager.getInstance().setOpenPingbao(false);
    }

    @OnClick(R.id.tv_name)
    public void onHighSetting(View view) {
        if (ClickHelper.click5Times()) {
            if (dialog == null) {
                dialog = PasswordInsureDialog.startPasswordInsure(getContext(), 1, new EventAction() {
                    @Override
                    public void onAction(int ID) {
                        startActivity(new Intent(getActivity(), SettingActivity.class));
                    }
                });
            } else {
                dialog.show();
            }
        }
    }

    @OnClick({R.id.tv_query, R.id.tv_borrow, R.id.tv_return, R.id.tv_renew, R.id.test_btn})
    public void onClick(View view) {
        super.onClick(view);
    }

    @Override
    protected void onClick2(View view) {
        if (!SocketChecker.getInstance().isConnected()) {
            SystemTTS.getInstance().playText("服务器连接失败");
            return;
        }
        int id = view.getId();
        switch (id) {
            case R.id.tv_query:
                SystemTTS.getInstance().playText("请将读者卡放入感应区");
                new PutCardDialog(getActivity()).cardListener(new PutCardDialog.OnCardReadListener() {
                    @Override
                    public void onComplete(String cardNo) {
                        queryBorrowBooksByReader(cardNo, true);
                    }
                }).show();
                break;
            case R.id.tv_borrow:
                SystemTTS.getInstance().playText("请将读者卡放入感应区");
                new PutCardDialog(getActivity()).cardListener(new PutCardDialog.OnCardReadListener() {
                    @Override
                    public void onComplete(String cardNo) {
                        queryReaderInfo(cardNo);
                    }
                }).show();

                break;
            case R.id.tv_return:
                BackScanBookDelegate backScanBookDelegate = findFragment(BackScanBookDelegate.class);
                if (backScanBookDelegate == null) {
                    backScanBookDelegate = BackScanBookDelegate.getInstance();
                }
                start(backScanBookDelegate);
                break;
            case R.id.tv_renew:
                SystemTTS.getInstance().playText("请将读者卡放入感应区");
                new PutCardDialog(getActivity()).cardListener(new PutCardDialog.OnCardReadListener() {
                    @Override
                    public void onComplete(String cardNo) {
                        queryBorrowBooksByReader(cardNo, false);
                    }
                }).show();
                break;
            default:
                break;
        }
    }

    @OnCheckedChanged({R.id.rb_chinese, R.id.rb_english})
    public void onchange(CompoundButton button, boolean isChecked) {
        if (button.getId() == R.id.rb_chinese) {
            if (isChecked) {
                if (!LanguageUtils.isAppliedLanguage(Locale.CHINA)) {
                    LanguageUtils.applyLanguage(Locale.CHINA, MainActivity.class);
                }
            }
        } else {
            if (isChecked) {
                if (!LanguageUtils.isAppliedLanguage(Locale.US)) {
                    LanguageUtils.applyLanguage(Locale.US, MainActivity.class);
                }
            }
        }
    }


    @Subscribe
    public void onUsbChange(USBChangeEvent event) {
//        String deviceName = DeviceManager.getInstance().getDeviceName(event.pid, event.vid);
//        if (deviceName != null) {
//            DeviceManager.getInstance().deviceChange(event.vid, event.pid, event.isAttach);
//            if (event.isAttach) {
//                SystemTTS.getInstance().playText(deviceName + "已连接");
//                if (getActivity() != null) {
//                    hasFoundCardReader = LotusCardUtils.getInstance().findDevice(getActivity());
//                }
//            } else {
//                SystemTTS.getInstance().playText(deviceName + "已断开");
//                hasFoundCardReader = false;
//            }
//        }
//        setDeviceInfoText();
    }

    private void setDeviceInfoText() {
        String info = DeviceManager.getInstance().getErrorInfo();
        if (info == null || info.isEmpty()) {
            if (getActivity() != null) {
                hasFoundCardReader = LotusCardUtils.getInstance().findDevice(getActivity());
            }
        }
        mTvDeviceInfo.setText(info);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        Log.e("HomeDelegate", "onDestroyView");
    }

    private void queryBorrowBooksByReader(String cardNo, boolean query) {
        RxHttp.get("cslinks/rest/BorrowBooklist")
                .add("ReaderBarcode", cardNo)
                .asString()
                .to(RxLife.toMain(HomeDelegate.this))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String readerInfo) throws Throwable {
                        if (readerInfo.contains("没有查询到当前借阅信息")) {
                            SystemTTS.getInstance().playText(readerInfo);
                        } else if (readerInfo.contains("不存在")) {
                            SystemTTS.getInstance().playText(readerInfo);
                        } else {
                            Gson gson = new Gson();
                            ArrayList<BorrowBookInfo> list = gson.fromJson(readerInfo, new TypeToken<ArrayList<BorrowBookInfo>>() {
                            }.getType());
                            if (query) {
                                QueryBookByUser queryBookByUser = findFragment(QueryBookByUser.class);
                                if (queryBookByUser == null) {
                                    queryBookByUser = QueryBookByUser.getInstance(cardNo, list);
                                }
                                start(queryBookByUser);
                            } else {
                                RenewBookDelegate renewBookDelegate = findFragment(RenewBookDelegate.class);
                                if (renewBookDelegate == null) {
                                    renewBookDelegate = RenewBookDelegate.getInstance(cardNo, list);
                                }
                                start(renewBookDelegate);
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        if (throwable.getMessage() != null && throwable.getMessage().contains("timed out")) {
                            SystemTTS.getInstance().playText("无法连接到服务器，请重试");
                        } else {
                            SystemTTS.getInstance().playText("信息获取失败，请重试");
                        }
                    }
                });
    }

    private void queryReaderInfo(String cardNo) {
        RxHttp.get("cslinks/rest/getReaderinforAll")
                .add("ReaderBarcode", cardNo)
                //.add("ReaderBarcode", "2233")
                .asString()
                .to(RxLife.toMain(HomeDelegate.this))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Throwable {
                        if (s.contains("不存在")) {
                            SystemTTS.getInstance().playText(s);
                        } else {
                            Gson gson = new Gson();
                            ArrayList<ReaderInfo> list = gson.fromJson(s, new TypeToken<ArrayList<ReaderInfo>>() {
                            }.getType());
                            if (list == null || list.isEmpty()) {
                                SystemTTS.getInstance().playText("未查询到该读者证信息");
                            } else {
                                start(BorrowScanBookDelegate.getInstance(list.get(0)));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        if (throwable.getMessage() != null && throwable.getMessage().contains("timed out")) {
                            SystemTTS.getInstance().playText("无法连接到服务器，请重试");
                        } else {
                            SystemTTS.getInstance().playText("信息获取失败，请重试");
                        }
                    }
                });
    }

}